package com.xapp.utils.httpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * @author YH_CK
 * @data 2018.09.19 10:00
 * @describe
 **/
public class ImageHttpUtils {
    private static final String TAG = ImageHttpUtils.class.getSimpleName();
    //正式环境
    // private static final String mAuthorizeURL = "https://xwf-api.yonghui.cn/XwfLoanFrontService/platFormAuth/authMerchant/0";
    //测试环境
    private static final String mAuthorizeURL = "https://xwf-test.yonghui.cn/XwfLoanFrontServiceUAT/platFormAuth/authMerchant/0";

    private static final int CONNECTION_TIMEOUT = 50000; //connection timeout time 50s
    private static final int READ_TIMEOUT = 50000; //data transfer timeout 50s
    private static final String CHARSET = "utf-8"; //设置编码
    private static final String PREFIX = "--";
    private static final String LINE_END = "\r\n";
    private static ImageHttpUtils instance = null;

    //Create a single object
    public static ImageHttpUtils getInstance() {
        if (instance == null) {
            instance = new ImageHttpUtils();
        }
        return instance;
    }

    /**
     * update image
     *
     * @param jsonData
     * @return
     */
    public String updateFilePostConn(String jsonData) {
        String result = "";
        String mURL = "";
        String mAuthHeader = "";
        List<ImageInfo> mImageInfoList = new ArrayList<>();
        String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成 String PREFIX = "--" , LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        try {
            JSONObject myJsonData = new JSONObject(jsonData);
            mURL = myJsonData.getString("url");
            mAuthHeader = myJsonData.getString("header");
            JSONArray mJsonArray = myJsonData.getJSONArray("imageArray");
            for (int i = 0; i < mJsonArray.length(); i++) {
                JSONObject jsonObject = (JSONObject) mJsonArray.get(i);
                ImageInfo imageInfoBean = new ImageInfo();
                imageInfoBean.setName(jsonObject.getString("name"));
                imageInfoBean.setPath(jsonObject.getString("path"));
                imageInfoBean.setImageParams(jsonObject.getString("params"));
                mImageInfoList.add(imageInfoBean);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {

            URL mUrl = new URL(mURL);
            //TODO 环境切换
            // HttpsURLConnection conn = (HttpsURLConnection) mUrl.openConnection();
            HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, tm, new SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            // TODO 设置域名校验
//            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
//            conn.setSSLSocketFactory(ssf);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);//连接主机超时
            conn.setReadTimeout(READ_TIMEOUT);//从主机读取数据超时
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("Charset", CHARSET);//设置编码
            JSONObject jsonHeader = new JSONObject(mAuthHeader);
            Iterator itKey = jsonHeader.keys();
            String headerKey = "";
            while (itKey.hasNext()) {
                headerKey = itKey.next().toString();
            }
            conn.setRequestProperty(headerKey, jsonHeader.getString(headerKey));//设置请求头
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            conn.setDoInput(true); //允许输入流
            conn.setDoOutput(true); //允许输出流
            conn.setUseCaches(false); //不允许使用缓存

            if (mImageInfoList.size() > 0) {
                /* 当文件不为空，把文件包装并且上传 */
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                for (ImageInfo imageEnty : mImageInfoList) {
                    File file = new File(imageEnty.getPath());
                    StringBuffer sb = new StringBuffer();
                    if (file != null) {
                        if (imageEnty.getImageParams() != null) {
                            JSONObject jsonParam = new JSONObject(imageEnty.getImageParams());
                            for (Iterator<?> iter = jsonParam.keys(); iter.hasNext(); ) {
                                Object key = iter.next();
                                sb.append(PREFIX).append(BOUNDARY).append(LINE_END);//分界符
                                sb.append("Content-Disposition: form-data; name=" + key.toString()).append(LINE_END);
                                sb.append("Content-Type: text/plain; charset=").append(CHARSET).append(LINE_END);
                                sb.append(LINE_END);
                                sb.append(jsonParam.getString(key.toString()));
                                sb.append(LINE_END);//换行
                            }
                        }
                        //开始拼接文件参数
                        sb.append(PREFIX).append(BOUNDARY).append(LINE_END);//分界符
                        /**
                         * 重点注意：
                         * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                         * filename是文件的名字，包含后缀名的 比如:abc.png
                         */
                        sb.append("Content-Disposition: form-data; name=" + "file" + "; filename=" + imageEnty.getName()).append(LINE_END);
                        sb.append("Content-Type: application/octet-stream; charset=").append(CHARSET).append(LINE_END);
                        sb.append(LINE_END);
                        //写入文件数据
                        dos.write(sb.toString().getBytes());
                        InputStream is = new FileInputStream(file);
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        while ((len = is.read(bytes)) != -1) {
                            dos.write(bytes, 0, len);
                        }
                        is.close();
                        dos.write(LINE_END.getBytes());//一定还有换行
                    }
                }
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功
                 * 当响应成功，获取响应的流
                 */
                //check the result of connection
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    //gets the read content
                    InputStreamReader in = new InputStreamReader(conn.getInputStream());
                    //gets the input stream object
                    BufferedReader buffer = new BufferedReader(in);
                    String inputLine = "";
                    while ((inputLine = buffer.readLine()) != null) {
                        result += inputLine + "\n";
                    }
                    in.close();
                }
                dos.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 检测是否https
     */
    private static boolean isHttps(String url) {
        return url.startsWith("https");
    }


    /**
     * 不进行主机名确认
     */
    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    /**
     * 信任所有主机 对于任何证书都不做SSL检测
     * 安全验证机制，而Android采用的是X509验证
     */
    private static class MyX509TrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    class ImageInfo {
        private String name;
        private String path;
        private String imageParams;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public String getImageParams() {
            return imageParams;
        }

        public void setImageParams(String imageParams) {
            this.imageParams = imageParams;
        }
    }
}
